<?php

namespace App\Http\Controllers\Admin;

use App\Model\Category;
use App\Services\CategoryService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

class CategoryController extends Controller
{
    public function index($type = null)
    {
        $keyword = Input::get('keyword');
        if(empty($type)||!in_array($type,array(Category::TYPE_CATE,Category::TYPE_TAG))){
            return self::error('参数错误');
        }
        $cate = new Category();
        $cate = $cate->where('type',$type);
        $page = Input::get('p',5);
        $categorys = $cate->get();
        if(empty($keyword)){
            $cateList = $cate->paginate($page);
        }else{
            $cateList = $cate->where('name','like','%'.$keyword.'%')->paginate($page);
        }
        $cateList->setPath(url('admin/category/index').'/'.$type.'?keyword='.$keyword);
        return view('admin.category.index',['categorys'=>$categorys,'cateList'=>$cateList,'type'=>$type,'keyword'=>$keyword]);
    }

    public function save()
    {
        $type = Input::get('type');
        $taxy = Input::get('taxy');
        if($type == 'add'){
            $category = new Category();
        }elseif($type == 'edit'){
            $id = Input::get('id');
            $category = Category::where('id',$id)->where('type',$taxy)->first();
            if(empty($category))
            {
                return self::apiFail('参数错误');
            }
        }else{
            return self::apiFail('参数错误');
        }
        $name   = Input::get('name');
        switch ($taxy){
            case Category::TYPE_CATE:
                $parent = Category::where('id',Input::get('parent'))->where('type',$taxy)->first();
                if(empty($parent)) {
                    return self::apiFail('父级目录不存在');
                }
                if($type == 'edit'){
                    $exist = Category::where('id','!=',$category->id)->where('type',$taxy)->where('name',$name)->first();
                    if(!empty($exist)){
                        return self::apiFail('存在同名目录');
                    }
                    $categorySrv = new CategoryService();
                    //父节点不能是当前节点的子孙节点
                    $children = $categorySrv->getChilds($category->id);
                    if(in_array($category->id,$children)){
                        return self::apiFail('');
                    }
                    //子孙节点的level偏移
                    $level = $parent->level + 1;
                    $shift = $level - $category->level;
                    foreach ($children as $child){
                        $cate = Category::where('id',$child)->first();
                        $cate->level = $cate->level + $shift;
                        $cate->save();
                    }
                    $category->level = $level;
                }elseif($type == 'add'){
                    $exist = Category::where('name',$name)->where('type',$taxy)->first();
                    if(!empty($exist)){
                        return self::apiFail('存在同名目录');
                    }
                    $category->level = $parent->level + 1;
                }
                $category->parent = Input::get('parent');
                $category->type   = $taxy;
                $category->icons  = Input::get('icons') ? Input::get('icons') : 'label';
                break;
            case Category::TYPE_TAG:
                if($type == 'edit'){
                    $exist = Category::where('id','!=',$category->id)->where('type',$taxy)->where('name',$name)->first();
                    if(!empty($exist)){
                        return self::apiFail('存在同名标签');
                    }
                }elseif($type == 'add'){
                    $exist = Category::where('name',$name)->where('type',$taxy)->first();
                    if(!empty($exist)){
                        return self::apiFail('存在同名标签');
                    }
                }
                $category->type  = $taxy;
                $category->level = Category::ROOT_LEVEL;
                break;
            default:
                return self::apiFail('系统错误');
        }

        $category->name     = Input::get('name');
        $category->descript = Input::get('descript');
        $category->save();
        $category->msg = '保存成功';
        return self::apiSucc($category);
    }

    public function remove()
    {
        $id = Input::get('id');
        $category = Category::where('id',$id)->first();
        if(empty($id)||empty($category)){
            return self::apiFail('参数错误');
        }
        $categorySrv = new CategoryService();
        $children = $categorySrv->getChilds($id);
        if(!empty($children)){
            return self::apiFail('不允许删除');
        }
        $category->delete();
        return self::apiSucc('删除成功!');
    }

    public function import(Request $request)
    {
        set_time_limit(600);
        if (!$request->hasFile('file')) {
            return self::apiFail('文件上传失败');
        }
        $file = $request->file('file');
        if (!$file->isValid()) {
            return self::apiFail('上传文件不合法');
        }
        $path = $request->file('file')->store('storage');
        $basePath = storage_path() . '/app/';
        $file = fopen($basePath . $path, 'r');
        $count = 0;
        $fails = 0;
        $type  = $request->input('type');
        while (($data = fgets($file)) != false){
            $count++;
            if ($count == 1) {
                continue;
            }
            $data = iconv('GBK', 'UTF-8', $data);
            $cates = preg_split('/\,/', $data);
            if(empty($cates[0])){
                $fails++;
                continue;
            }
            $exist = Category::where('name',$cates[0])->where('type',$type)->first();
            if(!empty($exist)){
                return self::apiFail('存在同名标签');
            }
            if($type == Category::TYPE_CATE){
                $parent = Category::where('name',trim($cates[2]))->where('type',$type)->first();
                if(empty($parent)){
                    $fails++;
                    continue;
                }else{
                    $level    = (int)$parent->level + 1;
                    $cates[2] = $parent->id;
                }
            }else{
                $level = Category::ROOT_LEVEL;
                $cates[2] = null;
            }
            if(empty($cates[1])){
                $cates[1] = 'default';
            }
            if(empty($cates[3])){
                $cates[3] = '一个无名氏标签';
            }
            $category = new Category();
            $category->name  = $cates[0];
            $category->icons = $cates[1];
            $category->level = $level;
            $category->parent   = $cates[2];
            $category->descript = preg_replace('/\\r\\n/','',$cates[3]);
            $category->type = $type;
            $category->save();
        }
        $succ = $count - $fails - 1;
        //unlink($basePath . $path);
        $msg = "$succ 条导入成功， $fails 条导入失败";
        return self::apiSucc($msg);
    }

    public function search()
    {
        $callback = Input::get('callback');
        $keyword  = Input::get('keyword');
        $type     = Input::get('type',Category::TYPE_CATE);
        $cates = Category::where('name','like','%'.$keyword.'%')->where('type',$type)->get();
        return self::apiSucc($cates,$callback);
    }

    public function listCates()
    {
        $callback = Input::get('callback');
        $type = Input::get('type',Category::TYPE_CATE);
        $name = Input::get('name','');
        $category = new Category();
        if(!empty($name)){
            $category = $category->where('name',$name);
        }
        if($type == Category::TYPE_CATE){
            $cates  = $category->where('type',Category::TYPE_CATE)->orderBy('created_at','desc')->paginate(5);
            //跨域调用标识
            $callback = Input::get('callback');
            return self::apiSucc($cates,$callback);
        }else if($type == Category::TYPE_TAG){
            $tags  = $category->where('type',Category::TYPE_TAG)->orderBy('created_at','desc')->paginate(5);
            //跨域调用标识
            $callback = Input::get('callback');
            return self::apiSucc($tags,$callback);
        }else{
            return self::apiFail('',$callback);
        }
    }

    public function catesCollections()
    {
        $callback = Input::get('callback');
        $type = Input::get('type');
        if(!in_array($type,array(Category::TYPE_CATE,Category::TYPE_TAG,Category::TYPE_ALL))){
            return self::apiFail('',$callback);
        }
        if($type != Category::TYPE_ALL){
            $cates = Category::where('type',$type)->get();
            return self::apiSucc($cates,$callback);
        }else{
            $cates = Category::where('type',Category::TYPE_CATE)->get();
            $tags = Category::where('type',Category::TYPE_TAG)->get();
            return self::apiSucc([$cates,$tags],$callback);
        }

    }
}
